﻿using Autofac;
using Autofac.Builder;
using Autofac.Features.Scanning;
using Autofac.Integration.WebApi;
using System;
using System.Linq;
using System.Reflection;
using System.Web.Http;
using XieCan.AspMVC.Helpers;

namespace XieCan.AspMVC.AutofacApi
{
    public class AutofacApiHelper
    {
        /// <summary>
        /// 获取线程内唯一ContainerBuilder对象
        /// </summary>
        private static ContainerBuilder ApiContainer => CallContextHelper.Single<ContainerBuilder>("ContainerBuilderApi");

        /// <summary>
        /// 执行注入
        /// </summary>
        public static void RegisterAllTypes(HttpConfiguration configuration)
        {
            var container = ApiContainer.Build();
            configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        /// <summary>
        /// 追加程序集
        /// </summary>
        /// <param name="assemblies">程序集</param>
        /// <param name="filter">注入类型过滤器</param>
        /// <param name="interfaces">是否注入为接口</param>
        /// <param name="roperties">是否为属性注入</param>
        /// <returns></returns>
        public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle> AppendAssembly(Func<Type, bool> filter = null, bool interfaces = false, bool roperties = true, params Assembly[] assemblies)
        {
            var result = ApiContainer.RegisterAssemblyTypes(assemblies);

            if (filter != null)
                result.Where(filter);

            if (interfaces)
                result.AsImplementedInterfaces();

            if (roperties)
                result.PropertiesAutowired();

            return result;
        }
    }
}
